import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

import 'utils/jsbridge.dart';
import 'jsmethod.dart';

typedef JSChannelRegisterHandler = void Function(
    String handleName, String data);

class InAppWebJSBridgeRegister {
  late InAppWebJSHandlerManager _inAppWebJSHandlerManager;
  InAppWebJSBridgeRegister(InAppWebJSHandlerManager inAppWebJSHandlerManager) {
    _inAppWebJSHandlerManager = inAppWebJSHandlerManager;
  }

  void registerHandlers({JSChannelRegisterHandler? jsChannelRegisterHandler}) {
    _inAppWebJSHandlerManager.registerHandler(JSChannelRegisterMethod.setTitle,
        (data, responseCallback) {
      if (data != null && data is String) {
        String title = data;
        if (jsChannelRegisterHandler != null) {
          jsChannelRegisterHandler(JSChannelRegisterMethod.setTitle, title);
        }
      }
    });
    // TODO: 自定义的方法注册到这里
    _inAppWebJSHandlerManager.registerHandler(JSChannelRegisterMethod.WtoF,
        (data, responseCallback) {
      if (data != null) {
        showDialog(
            context: _inAppWebJSHandlerManager.context!,
            builder: (BuildContext context) {
              return AlertDialog(
                title: const Text('flutter dialog'),
                actions: <Widget>[
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      responseCallback!({});
                      Navigator.pop(context, 'Cancle');
                    },
                  ),
                  TextButton(
                    child: const Text('发送消息给web'),
                    onPressed: () {
                      responseCallback!({});
                      _inAppWebJSHandlerManager
                          .callHandler('FtoW', {'data': "发给web的消息"}, (message) {
                        print('从web回调的$message');
                      });
                      Navigator.pop(context, "Ok");
                    },
                  ),
                  TextButton(
                    child: const Text('发送回调给web'),
                    onPressed: () {
                      responseCallback!({'data': "flutter 回调的消息数据"});
                      Navigator.pop(context, "Ok");
                    },
                  )
                ],
              );
            });
      }
    });

    _inAppWebJSHandlerManager.addJSBridgeHandlers();
  }

  // 处理是否跳转，true可跳转，false不可跳转
  bool shouldOverrideUrlLoading(Uri uri) {
    ///在页面跳转之前调用 isForMainFrame为false,页面不跳转.导致网页内很多链接点击没效果
    String url = uri.toString();
    return webViewNavigationAllowed(url);
  }

  void openLauncher(String urlStr) async {
    Uri uri = Uri.parse(urlStr);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    }
  }

  // 处理是否跳转，true可跳转，false不可跳转
  bool webViewNavigationAllowed(String url) {
    print('navigationDelegate decode $url');
    // 可以查看规则 https://pub.dev/packages/url_launcher
    List<String> prefixs = ["tel://", "sms://", "mailto://"];
    for (var element in prefixs) {
      if (url.startsWith(element)) {
        String data = url.replaceFirst('//', '');
        openLauncher(data);
        // 不可跳转
        return false;
      }
    }

    if (url == "about:blank") {
      // 空页面进行跳转
      return true;
    }

    // 可跳转
    return true;
  }
}
